from django.shortcuts import render, redirect
from django.urls import reverse
from apps.user.models import BlogUser
from utils.PageUtils import get_middle_range
from utils.StringUtil import StringUtil
from django.http.response import JsonResponse
from apps.article.models import Article, Comment
from django.core.paginator import Paginator


# Create your views here.

# 添加文章
def add(request):
    context = {}
    # 获取cookie
    username = request.COOKIES.get('username')
    # 判断
    if username is None:
        # 说明没有登录，跳转到登录页面
        return redirect(reverse('user:login'))
    return render(request, 'article/add.html', context)


# 执行添加文章
def add_do(request):
    # 第一步：获取文章信息
    title = request.POST.get('title')
    info = request.POST.get('info')
    content = request.POST.get('content')

    # print(title, info, content)
    # 第二步：添加文章到数据库
    Article.objects.create(
        title=title,  # 标题
        info=info,  # 信息
        content=content,  # 内容
    )

    # 第三步：渲染文章
    return redirect("/")


# 文章详情
def detail(request):
    username = request.COOKIES.get('username')
    if username is None:
        return redirect(reverse('user:login'))
    id = request.GET.get('id')
    article = Article.objects.get(id=id)
    article.view_num += 1
    article.save()
    # 得到所有的评论
    comments = Comment.objects.filter(article_id=id).order_by('-create_time')
    paginator = Paginator(comments, 3)
    # 当前页码是多少页
    page_num = request.GET.get('p', 1)
    # 得到当前页
    page = paginator.page(page_num)
    # 得到中间的页码
    middle_page = get_middle_range(list(paginator.page_range), int(page_num) - 1)
    context = {
        'article': article,
        'comments': page.object_list,
        "page": page,  # 分页对象
        "middle_page": middle_page,  # 中间页页码
        "current_page": int(page_num)  # 当前页
    }
    return render(request, 'article/detail.html', context)


# 点赞
def good(request):
    id = request.GET.get('id')
    article = Article.objects.get(id=id)
    # 增加点赞
    article.good_num += 1
    article.save()

    # 封装返回结果
    content = {
        'code': 10000,
        'msg': 'ok',
        'good_num': article.good_num
    }
    return JsonResponse(content)


def add_ajax(request):
    """ajax的方式添加文章"""
    # 提取数据
    author = request.POST.get('author')

    # 根据作者名称，查作者数据
    author_obj = BlogUser.objects.get(username=author)

    title = request.POST.get('title')
    info = request.POST.get('info')
    content = request.POST.get('content')

    # 数据清洗：xss攻击，script
    content = StringUtil.get_safe_html(content)
    # print("过滤后的内容：", content)

    # 数据入库
    Article.objects.create(
        user_id=author_obj.id,
        username=author,  # 作者名称
        title=title,  # 标题
        info=info,  # 信息
        content=content,  # 内容
    )

    # 返回json数据
    # 封装返回结果
    content = {
        'status': 200,
        'msg': 'ok',
    }
    return JsonResponse(content)


def add_comment(request):
    """ajax的方式添加评论"""
    try:
        username = request.POST.get("username")
        blog_user = BlogUser.objects.filter(username=username).first()
        user_id = blog_user.id
        user_avatar = blog_user.avatar
        article_id = request.POST.get("articleId")
        article = Article.objects.filter(id=article_id).first()
        article_title = article.title
        content = request.POST.get('comment')
        content = StringUtil.get_safe_html(content)
        Comment.objects.create(
            user_id=user_id,
            username=username,
            avatar=user_avatar,
            article_id=article_id,
            article_title=article_title,
            content=content,
        )
        content = {
            'code': 10000,
            'msg': 'ok',
        }
        return JsonResponse(content)
    except Exception as e:
        print(e)
        content = {
            'code': 20000,
            'msg': 'error',
        }
        return JsonResponse(content)
